package com.example.adminsystem.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import com.example.adminsystem.common.ResponseResult;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.DataException;
import org.springframework.dao.DataIntegrityViolationException;
import java.sql.SQLException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ResponseResult<?>> handleGlobalException(Exception ex, WebRequest request) {
        String errorMessage = buildErrorMessage(ex);
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ResponseResult.error(errorMessage));
    }

    private String buildErrorMessage(Exception ex) {
        if (ex instanceof DataIntegrityViolationException) {
            Throwable rootCause = ((DataIntegrityViolationException) ex).getRootCause();
            if (rootCause instanceof DataException) {
                DataException dataEx = (DataException) rootCause;
                SQLException sqlEx = dataEx.getSQLException();
                return String.format(
                    "数据库完整性违反错误:\n" +
                    "- 错误类型: %s\n" +
                    "- 根本原因: %s\n" +
                    "- SQL状态码: %s\n" +
                    "- 错误代码: %d\n" +
                    "- 详细原因: %s",
                    dataEx.getClass().getSimpleName(),
                    dataEx.getMessage(),
                    sqlEx.getSQLState(),
                    sqlEx.getErrorCode(),
                    sqlEx.getMessage());
            } else if (rootCause instanceof ConstraintViolationException) {
                ConstraintViolationException cve = (ConstraintViolationException) rootCause;
                return String.format(
                    "数据约束违反错误:\n" +
                    "- 约束名称: %s\n" +
                    "- 详细原因: %s",
                    cve.getConstraintName(),
                    cve.getSQLException().getMessage());
            }
            return String.format("数据完整性错误: %s", rootCause != null ? rootCause.getMessage() : ex.getMessage());
        }
        return String.format("系统错误: %s\n错误类型: %s", 
            ex.getMessage(), 
            ex.getClass().getSimpleName());
    }
}
